//
//  MarketFlowViewController.m
//  BondWatch
//
//  Created by Jason Yuan on 12/1/15.
//  Copyright © 2015 Jason Yuan. All rights reserved.
//

#import "MarketFlowViewController.h"
#import "MarketFlowTableViewCell.h"

@interface MarketFlowViewController () <UITableViewDelegate, UITableViewDataSource>
{
    UIScrollView *myScrollView;
    UITableView *myTableView;
    NSArray *dataArray;
    
    UILabel *totalLabel;
    UILabel *volumeTotalLabel;
    UILabel *ratioTotalLabel;
    UILabel *averageTotalLabel;
    UILabel *changeTotalLabel;
    UILabel *dealerTotalLabel;
}

@end

@implementation MarketFlowViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Secondary Market Flow";
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetica-Bold" size:18.0],
        NSFontAttributeName, nil]];
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonItemPressed:)];
    self.navigationItem.leftBarButtonItem = settingBarButton;
    
    UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Refresh"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshBarButtonPressed:)];
    self.navigationItem.rightBarButtonItem = refreshBarButton;
    
    myScrollView = [[UIScrollView alloc] init];
    myScrollView.bounces = NO;
    [myScrollView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:myScrollView];
    myScrollView.contentSize = CGSizeMake(500.0, 0);
    
    myTableView = [[UITableView alloc] init];
    if ([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft ||
        [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight) {
        myTableView.frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height - 30);
    } else {
        myTableView.frame = CGRectMake(0, 0, 500, self.view.bounds.size.height - 64);
    }
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.bounces = NO;
    myTableView.separatorInset = UIEdgeInsetsZero;
    myTableView.layoutMargins = UIEdgeInsetsZero;
    [myScrollView addSubview:myTableView];
    
    [myScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}

- (void)settingBarButtonItemPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)refreshBarButtonPressed:(id)sender {
    [self getData];
}

- (void)getData {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 100.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager GET:MARKETFLOWURL parameters:nil success:^(NSURLSessionDataTask *task, id JSON) {
        NSString *string = [[NSString alloc] initWithData:JSON encoding:NSUTF8StringEncoding];
        dataArray = [string objectFromJSONString];
        DDLogVerbose(@"Market Flow data is:\n%@", dataArray);
        [myTableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        if (response.statusCode == 200) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        
        DDLogError(@"Get Market Flow error:\n%@", error);
        NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        DDLogError(@"Get Market Flow error Message:\n%@", result);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Setting Rotate

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIDeviceOrientationLandscapeRight ||
        toInterfaceOrientation == UIDeviceOrientationLandscapeLeft) {
        myTableView.frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height - 30);
    } else {
        myTableView.frame = CGRectMake(0, 0, 500, self.view.bounds.size.height - 64);
    }
    [myTableView reloadData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (![dataArray isEqual:[NSNull null]]) {
        return [dataArray count];
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MarketFlowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MarketFlow"];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[MarketFlowTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MarketDetail"];
        cell.separatorInset = UIEdgeInsetsZero;
    }
    NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.row];
    
    [cell setUIFrame];
    if (indexPath.row < [dataArray count]) {
        [cell setLabelText:dictionary];
    }
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.separatorInset = UIEdgeInsetsZero;
    cell.layoutMargins = UIEdgeInsetsZero;
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 580.0, 40.0)];
    [headerView setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0]];
    
    UILabel *sectorLabel;
    UILabel *volumeLabel1;
    UILabel *volumeLabel2;
    UILabel *ratioLabel1;
    UILabel *ratioLabel2;
    UILabel *averageLabel1;
    UILabel *averageLabel2;
    UILabel *changeLabel;
    UILabel *dealerLabel1;
    UILabel *dealerLabel2;
    
    sectorLabel = [[UILabel alloc] init];
    sectorLabel.textAlignment = NSTextAlignmentLeft;
    sectorLabel.font = ARIALBOLD10;
    sectorLabel.text = @"Sector";
    sectorLabel.textColor = [UIColor blueColor];
    
    volumeLabel1 = [[UILabel alloc] init];
    volumeLabel1.textAlignment = NSTextAlignmentRight;
    volumeLabel1.font = ARIALBOLD10;
    volumeLabel1.text = @"Weekly";
    volumeLabel1.textColor = [UIColor blueColor];
    
    volumeLabel2 = [[UILabel alloc] init];
    volumeLabel2.textAlignment = NSTextAlignmentRight;
    volumeLabel2.font = ARIALBOLD10;
    volumeLabel2.text = @"Volume $mln";
    volumeLabel2.textColor = [UIColor blueColor];
    
    ratioLabel1 = [[UILabel alloc] init];
    ratioLabel1.textAlignment = NSTextAlignmentRight;
    ratioLabel1.font = ARIALBOLD10;
    ratioLabel1.text = @"Weekly";
    ratioLabel1.textColor = [UIColor blueColor];
    
    ratioLabel2 = [[UILabel alloc] init];
    ratioLabel2.textAlignment = NSTextAlignmentRight;
    ratioLabel2.font = ARIALBOLD10;
    ratioLabel2.text = @"B/S Ratio";
    ratioLabel2.textColor = [UIColor blueColor];
    
    averageLabel1 = [[UILabel alloc] init];
    averageLabel1.textAlignment = NSTextAlignmentRight;
    averageLabel1.font = ARIALBOLD10;
    averageLabel1.text = @"Weekly Vol";
    averageLabel1.textColor = [UIColor blueColor];
    
    averageLabel2 = [[UILabel alloc] init];
    averageLabel2.textAlignment = NSTextAlignmentRight;
    averageLabel2.font = ARIALBOLD10;
    averageLabel2.text = @"Avg $mln";
    averageLabel2.textColor = [UIColor blueColor];
    
    changeLabel = [[UILabel alloc] init];
    changeLabel.textAlignment = NSTextAlignmentRight;
    changeLabel.font = ARIALBOLD10;
    changeLabel.text = @"Weekly";
    changeLabel.textColor = [UIColor blueColor];
    
    dealerLabel1 = [[UILabel alloc] init];
    dealerLabel1.textAlignment = NSTextAlignmentRight;
    dealerLabel1.font = ARIALBOLD10;
    dealerLabel1.text = @"Delaer-to-";
    dealerLabel1.textColor = [UIColor blueColor];
    
    dealerLabel2 = [[UILabel alloc] init];
    dealerLabel2.textAlignment = NSTextAlignmentRight;
    dealerLabel2.font = ARIALBOLD10;
    dealerLabel2.text = @"Dealer(%)";
    dealerLabel2.textColor = [UIColor blueColor];
    
    [headerView addSubview:sectorLabel];
    [headerView addSubview:volumeLabel1];
    [headerView addSubview:volumeLabel2];
    [headerView addSubview:ratioLabel1];
    [headerView addSubview:ratioLabel2];
    [headerView addSubview:averageLabel1];
    [headerView addSubview:averageLabel2];
    [headerView addSubview:changeLabel];
    [headerView addSubview:dealerLabel1];
    [headerView addSubview:dealerLabel2];
    
    [sectorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(2);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(120);
    }];
    
    [volumeLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sectorLabel.mas_right).offset(5);
        make.top.equalTo(headerView).offset(9);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [volumeLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sectorLabel.mas_right).offset(5);
        make.top.equalTo(volumeLabel1.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [ratioLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(volumeLabel1.mas_right).offset(5);
        make.top.equalTo(headerView).offset(9);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [ratioLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(volumeLabel2.mas_right).offset(5);
        make.top.equalTo(ratioLabel1.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [averageLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ratioLabel1.mas_right).offset(5);
        make.top.equalTo(headerView).offset(9);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [averageLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ratioLabel2.mas_right).offset(5);
        make.top.equalTo(averageLabel1.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [changeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(averageLabel1.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(80);
    }];
    
    [dealerLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(changeLabel.mas_right).offset(5);
        make.top.equalTo(headerView).offset(9);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    [dealerLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(changeLabel.mas_right).offset(5);
        make.top.equalTo(dealerLabel1.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(80, 10));
    }];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 30.0;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 580.0, 30.0)];
    [footerView setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0]];
    
    totalLabel = [[UILabel alloc] init];
    totalLabel.textAlignment = NSTextAlignmentLeft;
    totalLabel.font = ARIALBOLDITALIC10;
    
    volumeTotalLabel = [[UILabel alloc] init];
    volumeTotalLabel.textAlignment = NSTextAlignmentRight;
    volumeTotalLabel.font = ARIAL10;
    
    ratioTotalLabel = [[UILabel alloc] init];
    ratioTotalLabel.textAlignment = NSTextAlignmentRight;
    ratioTotalLabel.font = ARIAL10;
    
    averageTotalLabel = [[UILabel alloc] init];
    averageTotalLabel.textAlignment = NSTextAlignmentRight;
    averageTotalLabel.font = ARIAL10;
    
    changeTotalLabel = [[UILabel alloc] init];
    changeTotalLabel.textAlignment = NSTextAlignmentRight;
    changeTotalLabel.font = ARIAL10;
    
    dealerTotalLabel = [[UILabel alloc] init];
    dealerTotalLabel.textAlignment = NSTextAlignmentRight;
    dealerTotalLabel.font = ARIAL10;
    
    [footerView addSubview:totalLabel];
    [footerView addSubview:volumeTotalLabel];
    [footerView addSubview:ratioTotalLabel];
    [footerView addSubview:averageTotalLabel];
    [footerView addSubview:changeTotalLabel];
    [footerView addSubview:dealerTotalLabel];
    
    [totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footerView).offset(2);
        make.bottom.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(120, 30));
    }];
    
    [volumeTotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(totalLabel.mas_right).offset(5);
        make.bottom.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    [ratioTotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(volumeTotalLabel.mas_right).offset(5);
        make.bottom.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    [averageTotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ratioTotalLabel.mas_right).offset(5);
        make.bottom.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    [changeTotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(averageTotalLabel.mas_right).offset(5);
        make.bottom.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    [dealerTotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(changeTotalLabel.mas_right).offset(5);
        make.bottom.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    CGFloat volume = 0.0;
    CGFloat ratio = 0.0;
    CGFloat average = 0.0;
    CGFloat change = 0.0;
    CGFloat dealer = 0.0;
    
    for (NSDictionary *dictionary in dataArray) {
        NSNumber *volumeNumber = [dictionary objectForKey:@"volume"];
        volume += [volumeNumber floatValue];
        
        NSNumber *ratioNumber = [dictionary objectForKey:@"buySellRatio"];
        ratio += [ratioNumber floatValue];
        
        NSNumber *averageNumber = [dictionary objectForKey:@"volumeAverage"];
        average += [averageNumber floatValue];
        
        NSNumber *changeNumber = [dictionary objectForKey:@"volumeChange"];
        change += [changeNumber floatValue];
        
        NSNumber *dealerNumber = [dictionary objectForKey:@"dealerPercentage"];
        dealer += [dealerNumber floatValue];
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    
    NSInteger totalNumber = [dataArray count];
    
    totalLabel.text = @"Total";
    
    volumeTotalLabel.text = [formatter stringFromNumber:[NSNumber numberWithFloat:volume]];
    
    ratioTotalLabel.text = [NSString stringWithFormat:@"%.2f", ratio/totalNumber];
    
    averageTotalLabel.text = [formatter stringFromNumber:[NSNumber numberWithFloat:average]];
    
    changeTotalLabel.text = [NSString stringWithFormat:@"%.2f%%", change/totalNumber];
    
    dealerTotalLabel.text = [NSString stringWithFormat:@"%.2f%%", dealer/totalNumber];
    
    return footerView;
}

@end
